import React, { useState, useCallback } from 'react';
import { Box, Text, useInput } from 'ink';
import { ChineseInputHandler } from '../utils/chineseInput';
import { ThemeConfig } from '../types';

interface InputAreaProps {
  value: string;
  onChange: (value: string) => void;
  onSubmit: (value: string) => void;
  disabled?: boolean;
  theme: ThemeConfig;
}

const InputArea: React.FC<InputAreaProps> = ({
  value,
  onChange,
  onSubmit,
  disabled = false,
  theme
}) => {
  const [cursorPosition, setCursorPosition] = useState(0);
  const [inputHistory, setInputHistory] = useState<string[]>([]);
  const [historyIndex, setHistoryIndex] = useState(-1);

  useInput((input, key) => {
    if (disabled) return;

    if (key.return) {
      // Enter键发送消息
      if (value.trim()) {
        setInputHistory(prev => [value, ...prev.slice(0, 49)]); // 保留50条历史
        setHistoryIndex(-1);
        onSubmit(value);
        setCursorPosition(0);
      }
      return;
    }

    if (key.backspace || key.delete) {
      // Backspace删除字符
      if (cursorPosition > 0) {
        const newValue = ChineseInputHandler.deleteAtPosition(value, cursorPosition);
        onChange(newValue);
        setCursorPosition(cursorPosition - 1);
      }
      return;
    }

    if (key.leftArrow) {
      // 左箭头移动光标
      setCursorPosition(Math.max(0, cursorPosition - 1));
      return;
    }

    if (key.rightArrow) {
      // 右箭头移动光标
      const maxPosition = Array.from(value).length;
      setCursorPosition(Math.min(maxPosition, cursorPosition + 1));
      return;
    }

    if (key.upArrow) {
      // 上箭头查看历史
      if (inputHistory.length > 0) {
        const newIndex = Math.min(historyIndex + 1, inputHistory.length - 1);
        setHistoryIndex(newIndex);
        const historyValue = inputHistory[newIndex];
        onChange(historyValue);
        setCursorPosition(Array.from(historyValue).length);
      }
      return;
    }

    if (key.downArrow) {
      // 下箭头查看历史
      if (historyIndex >= 0) {
        const newIndex = historyIndex - 1;
        if (newIndex >= 0) {
          setHistoryIndex(newIndex);
          const historyValue = inputHistory[newIndex];
          onChange(historyValue);
          setCursorPosition(Array.from(historyValue).length);
        } else {
          setHistoryIndex(-1);
          onChange('');
          setCursorPosition(0);
        }
      }
      return;
    }

    if (key.ctrl && input === 'a') {
      // Ctrl+A移动到行首
      setCursorPosition(0);
      return;
    }

    if (key.ctrl && input === 'e') {
      // Ctrl+E移动到行尾
      setCursorPosition(Array.from(value).length);
      return;
    }

    // 普通字符输入
    if (input && !key.ctrl && !key.meta) {
      const newValue = ChineseInputHandler.insertAtPosition(value, cursorPosition, input);
      onChange(newValue);
      setCursorPosition(cursorPosition + 1);
    }
  }, { isActive: !disabled });

  const displayValue = useCallback(() => {
    if (!value) return '';
    
    const chars = Array.from(value);
    const beforeCursor = chars.slice(0, cursorPosition).join('');
    const atCursor = chars[cursorPosition] || ' ';
    const afterCursor = chars.slice(cursorPosition + 1).join('');
    
    return (
      <Text>
        <Text color={theme.inputArea}>{beforeCursor}</Text>
        <Text color={theme.inputArea} inverse>{atCursor}</Text>
        <Text color={theme.inputArea}>{afterCursor}</Text>
      </Text>
    );
  }, [value, cursorPosition, theme.inputArea]);

  const getStatusText = () => {
    if (disabled) return '等待回复中...';
    if (value.length === 0) return '输入您的消息...';
    
    const displayWidth = ChineseInputHandler.getDisplayWidth(value);
    return `字符数: ${Array.from(value).length} | 显示宽度: ${displayWidth}`;
  };

  return (
    <Box flexDirection="column" paddingX={1}>
      <Box>
        <Text color={theme.inputArea} bold>
          输入: 
        </Text>
        {displayValue()}
      </Box>
      
      <Box justifyContent="space-between" marginTop={1}>
        <Text color="gray" dimColor>
          {getStatusText()}
        </Text>
        
        {inputHistory.length > 0 && historyIndex >= 0 && (
          <Text color="gray" dimColor>
            历史 {historyIndex + 1}/{inputHistory.length}
          </Text>
        )}
      </Box>
    </Box>
  );
};

export default InputArea;